﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using COMOSOFT.Class;
using System.Data.SqlClient;
using DevExpress.XtraGrid.Views.Grid;

namespace COMOSOFT.Production.Forms
{
    public partial class FrmDeliveryView : Form
    {
        ClassShare cls = new ClassShare("FrmDeliveryView");
        FrmPreviewDeliveryDetails frPvDD = null;
        List<string> ListItem = new List<string>();
        int DID,OID,OldValue=-1;
        string info = "";
        Dictionary<int, int> ListPO;
        bool AutoPO=false;
        public FrmDeliveryView(int _DID)
        {
            InitializeComponent();
            this.DID = _DID;
        }

        private void FrmDeliveryView_Load(object sender, EventArgs e)
        {            
        }

        #region[AddNew]
        public void AddNew()
        {
            deliveryMasterBindingSource.AddNew();
            txt_ShipDate.EditValue = DateTime.Now;
            txt_Handler.EditValue = ClassShare.Usname;
        }
        #endregion

        #region[LoadData]
        public void LoadData()
        {
            sp_CustomerListTableAdapter.Fill(dataSet_Delivery.sp_CustomerList,ClassShare.Usid);
            sp_DeliveryChoosePOTableAdapter.Fill(this.dataSet_Delivery.sp_DeliveryChoosePO);
            factoryListTableAdapter.Fill(this.dataSet_Delivery.FactoryList);
            if (DID > 0)
            {
                deliveryMasterTableAdapter.Fill(this.dataSet_Delivery.DeliveryMaster,DID);
                sp_DeliveryDetailsTableAdapter.Fill(dataSet_Delivery.sp_DeliveryDetails, DID);
                if (groupControl_DeliveryDetial.Enabled == false)
                    groupControl_DeliveryDetial.Enabled = true;
                gridView_DeliveryDetails.ColumnPanelRowHeight=30;
            }
        }
        #endregion

        #region[Update Delivery Master]
        private void dataNavigator_ChoosePO_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            try
            {
                if (e.Button.Tag.ToString() == "Add")
                {
                    SqlConnection con = cls.connection();
                    GridView view = gridView_ChoosePO as GridView;
                    int[] arrOIDs = view.GetSelectedRows();
                    foreach (int index in arrOIDs)
                    {
                        OID=Convert.ToInt32(view.GetDataRow(index)["OID"]);
                        SqlCommand com1 = new SqlCommand("insert into DeliveryDetail (OID,DID,ShipQty) values (@OID,@DID,@ShipQty)", con);
                        com1.Parameters.AddWithValue("@OID", OID);
                        com1.Parameters.AddWithValue("@DID", DID);
                        com1.Parameters.AddWithValue("@DID", Convert.ToInt16(view.GetDataRow(index)["Quantity"]));
                        com1.ExecuteNonQuery();
                        //Update Status Order
                        SqlCommand com2 = new SqlCommand("update OrderDetails set Status=@status where OID=@OID", con);
                        com2.Parameters.AddWithValue("@status", "Finished");
                        com2.Parameters.AddWithValue("@OID", OID);
                        com2.ExecuteNonQuery();
                    }
                    LoadData();
                    con.Close();
                }
                else
                {
                    if (e.Button.Tag.ToString() == "Refresh")
                        sp_DeliveryChoosePOTableAdapter.Fill(this.dataSet_Delivery.sp_DeliveryChoosePO);
                    else
                        this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void UpdateData(string com)
        {
            try
            {
                if (com == "Update")
                {
                    deliveryMasterBindingSource.EndEdit();
                    deliveryMasterTableAdapter.Update(dataSet_Delivery.DeliveryMaster);
                    dataSet_Delivery.DeliveryMaster.AcceptChanges();
                    DID = Convert.ToInt32(txt_DID.EditValue);
                    this.Text ="ContNo: "+ txt_ContNo.EditValue.ToString();
                    if (AutoPO == true)
                    {
                        UpdateDD();
                        AutoPO = false;
                    }
                }
                else
                {
                    if (MessageBox.Show("Are you sure delete this object?", "Confirm Delete...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        dataSet_Delivery.DeliveryMaster.Rows[0].Delete();
                        deliveryMasterTableAdapter.Update(dataSet_Delivery.DeliveryMaster);
                        dataSet_Delivery.DeliveryMaster.AcceptChanges();
                    }
                }
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Update Delivery Details]
        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                GridView view=gridView_DeliveryDetails as GridView;
                if(view.FocusedRowHandle>=0)
                {
                    if (MessageBox.Show("Are you sure delete item?", "Confirm delete...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        SqlConnection con = cls.connection();
                        SqlCommand com = new SqlCommand("delete from DeliveryDetail where DDID=@DDID", con);
                        com.Parameters.AddWithValue("@DDID", Convert.ToInt32(view.GetFocusedDataRow()["DDID"]));
                        com.ExecuteNonQuery();
                        con.Close();
                    }
                }
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadData();
        }
        #endregion

        #region[ShipQty]
        private void gridView_DeliveryDetails_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                SqlConnection con = cls.connection();
                if (e.Column.FieldName == "ShipQty")
                {
                    if (!Convert.IsDBNull(e.Value))
                    {
                        if (Convert.ToInt32(e.Value) != OldValue)
                        {
                            info = ClassShare.Usname + " Ship Qty: " + OldValue + " --> " + Convert.ToInt32(e.Value)+" ("+DateTime.Now.ToShortDateString()+")";                            
                            SqlCommand com = new SqlCommand("update DeliveryDetail set ShipQty=@ShipQty, Tracking=@Tracking where DDID=@DDID", con);
                            com.Parameters.AddWithValue("@ShipQty", Convert.ToInt32(e.Value));
                            com.Parameters.AddWithValue("@Tracking", info);
                            com.Parameters.AddWithValue("@DDID", Convert.ToInt32(gridView_DeliveryDetails.GetFocusedDataRow()["DDID"]));
                            com.ExecuteNonQuery();
                        }
                    }
                }
                else
                {
                    if (e.Column.FieldName == "PackingMethod")
                    {
                        SqlCommand com = new SqlCommand("update DeliveryDetail set PackingMethod=@PM where DDID=@DDID", con);                       
                        com.Parameters.AddWithValue("@PM", e.Value.ToString());
                        com.Parameters.AddWithValue("@DDID", Convert.ToInt32(gridView_DeliveryDetails.GetFocusedDataRow()["DDID"]));
                        com.ExecuteNonQuery();
                    }
                }
                cls.connection().Close();
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gridView_DeliveryDetails_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "ShipQty")
            {
                if (!Convert.IsDBNull(e.CellValue)) 
                    OldValue = Convert.ToInt32(e.CellValue);
                else
                    OldValue = 0;
            }
        }
        #endregion

        #region[setvalue]
        public void SetValue(Dictionary<int,int> dicPO)
        {
            ListPO = dicPO;
            AutoPO = true;
        }
        #endregion

        #region[UPdate DeliveryDetails]
        public void UpdateDD()
        {
            try
            {
                SqlConnection con = cls.connection();
                if (ListPO.Count() > 0)
                {
                    foreach (var item in ListPO)
                    {
                        SqlCommand com1 = new SqlCommand("insert into DeliveryDetail (DID,OID,ShipQty) values (@DID,@OID,@ShipQty)", con);
                        com1.Parameters.AddWithValue("@DID", DID);
                        com1.Parameters.AddWithValue("@OID", item.Key);
                        com1.Parameters.AddWithValue("@ShipQty", item.Value);
                        com1.ExecuteNonQuery();
                        //Update Status Order
                        SqlCommand com2 = new SqlCommand("update OrderDetails set Status=@status where OID=@OID", con);
                        com2.Parameters.AddWithValue("@status", "Finished");
                        com2.Parameters.AddWithValue("@OID", item.Key);
                        com2.ExecuteNonQuery();
                    }
                }
                con.Close();
                ListPO.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Preview]
        private void previewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (frPvDD != null && !frPvDD.IsDisposed)
            {
                frPvDD.Select();
                frPvDD.LoadData();
            }
            else
            {
                ListItem.Clear();
                ListItem.Add(txt_Cus.EditValue.ToString());
                ListItem.Add(txt_ContNo.EditValue.ToString());
                ListItem.Add(txt_ContSize.EditValue.ToString());               
                ListItem.Add(txt_Description.EditValue.ToString());
                ListItem.Add(txt_ShipMode.EditValue.ToString());
                ListItem.Add(txt_ShipDate.EditValue.ToString());
                ListItem.Add(txt_Handler.EditValue.ToString());
                frPvDD = new FrmPreviewDeliveryDetails(gridView_DeliveryDetails, ListItem);
                frPvDD.LoadData();
                frPvDD.Show();
            }
        }
        #endregion
    }
}